/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * DeInsertPanel.java
 *
 * Created on 27/11/2011, 20:04:16
 */
package proj5labbd.graphics.departamento;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Formatter;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import proj5labbd.DBInterface;
import proj5labbd.DBInterface.DBQuery;
import proj5labbd.graphics.abstractOpGraphics.OperationPanel;

/*
 * Painel para inserção de departamentos na base de ados
 */
public class DeInsertPanel extends OperationPanel {

    /** Creates new form DeInsertPanel */
    public DeInsertPanel(DeptFrame frame, DBInterface dbInterface) throws SQLException {
        super(frame, dbInterface);
        initComponents();
        jbtInsert.addActionListener(new DeptAction());
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jpnParam = new javax.swing.JPanel();
        jlbNome = new javax.swing.JLabel();
        jftxtTel = new javax.swing.JFormattedTextField();
        jlbTel = new javax.swing.JLabel();
        jtxtNome = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        jtbInsert = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jtxtNFunc = new javax.swing.JTextField();
        jbtInsert = new javax.swing.JButton();

        setBorder(javax.swing.BorderFactory.createTitledBorder("Inserção"));
        addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                formMouseClicked(evt);
            }
        });
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentShown(java.awt.event.ComponentEvent evt) {
                formComponentShown(evt);
            }
        });

        jpnParam.setBorder(javax.swing.BorderFactory.createTitledBorder("Parâmetros de inserção"));

        jlbNome.setText("Nome");

        try {
            jftxtTel.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##########")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        jftxtTel.setFocusLostBehavior(javax.swing.JFormattedTextField.COMMIT);

        jlbTel.setText("Telefone");

        jtbInsert.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jtbInsert.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane1.setViewportView(jtbInsert);

        jLabel1.setText("Emissora:");

        jLabel2.setText("Nro. de funcionários");

        jtxtNFunc.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jtxtNFuncActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jpnParamLayout = new javax.swing.GroupLayout(jpnParam);
        jpnParam.setLayout(jpnParamLayout);
        jpnParamLayout.setHorizontalGroup(
            jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpnParamLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 550, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jpnParamLayout.createSequentialGroup()
                        .addGroup(jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jpnParamLayout.createSequentialGroup()
                                .addComponent(jlbNome, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(194, 194, 194))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jpnParamLayout.createSequentialGroup()
                                .addGroup(jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(jtxtNFunc, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 267, Short.MAX_VALUE)
                                    .addComponent(jtxtNome, javax.swing.GroupLayout.DEFAULT_SIZE, 267, Short.MAX_VALUE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)))
                        .addGroup(jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jlbTel)
                            .addComponent(jftxtTel, javax.swing.GroupLayout.DEFAULT_SIZE, 271, Short.MAX_VALUE)))
                    .addComponent(jLabel2)
                    .addComponent(jLabel1))
                .addContainerGap())
        );
        jpnParamLayout.setVerticalGroup(
            jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpnParamLayout.createSequentialGroup()
                .addGroup(jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jlbNome)
                    .addComponent(jlbTel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jtxtNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jftxtTel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jtxtNFunc, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 230, Short.MAX_VALUE)
                .addContainerGap())
        );

        jbtInsert.setText("Inserir");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jpnParam, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGap(12, 12, 12))
                    .addComponent(jbtInsert, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(jpnParam, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jbtInsert))
        );
    }// </editor-fold>//GEN-END:initComponents

    //ação ocorrida à apresentação do painel para o usuário
    private void formComponentShown(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentShown
        try {
            // TODO add your handling code here:
            setupTable();
        } catch (SQLException ex) {
            Logger.getLogger(DeInsertPanel.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_formComponentShown

    //ação ocorrida com o evento de click de mouse no painel
    private void formMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseClicked
        // TODO add your handling code here:
        jtbInsert.clearSelection();
    }//GEN-LAST:event_formMouseClicked

    private void jtxtNFuncActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jtxtNFuncActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jtxtNFuncActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton jbtInsert;
    javax.swing.JFormattedTextField jftxtTel;
    private javax.swing.JLabel jlbNome;
    private javax.swing.JLabel jlbTel;
    private javax.swing.JPanel jpnParam;
    private javax.swing.JTable jtbInsert;
    private javax.swing.JTextField jtxtNFunc;
    javax.swing.JTextField jtxtNome;
    // End of variables declaration//GEN-END:variables
    //cnfiguração da(s) tabela(s) utilizando dados resgatados na base de dados
    private void setupTable() throws SQLException {
        String [] fields = {"cnpjEm","nomeCompletoEm"};
        String [][] s = dbInterface.view(fields, null, new String[] {"emissora"});
    
        DefaultTableModel modelIn = new DefaultTableModel(s,new String[]{"CNPJ","Nome"});
        jtbInsert.setModel(modelIn);
        jtbInsert.setRowSelectionAllowed(true);
    }
    
    //ouvinte do botão de inserção
    class DeptAction implements ActionListener {

        //atuação do botão de inserção
        public void actionPerformed(ActionEvent e) {

            if ( e.getSource() == jbtInsert ) {

                if ( jtbInsert.getSelectedRowCount() == 1 && jtxtNome.getText().trim() != "") {
                    ArrayList<String> params = new ArrayList<String>();
                    ArrayList<String> fields = new ArrayList<String>();

                    params.add("SEQ_DEPARTAMENTO_IDDE.NEXTVAL");
                    fields.add("idDe");
                    params.add("'"+jtxtNome.getText()+"'");
                    fields.add("nomeDe");

                    if (jftxtTel.getText() != "          ") {
                        params.add(jftxtTel.getText());
                        fields.add("telefoneDe");
                    }
                    if (jtxtNFunc.getText().trim().compareTo("") != 0) {
                        params.add(jtxtNFunc.getText());
                        fields.add("nroFuncionariosDe");
                    }

                    params.add("'"+(String)jtbInsert.getValueAt(jtbInsert.getSelectedRow(), 0)+"'");
                    fields.add("cnpjEm");

                    String [] paramArray = new String[params.size()];
                    String [] fieldArray = new String[fields.size()];

                    params.toArray(paramArray);
                    fields.toArray(fieldArray);
                    try {
                        dbInterface.insert(fieldArray, paramArray, new String[]{"departamento"});
                    } catch (SQLException ex) {
                        frame.printException(ex);
                        JOptionPane.showMessageDialog(null, "Erro ao tentar inserir a tupla.");
                    }

                }
                else if (jtbInsert.getSelectedRowCount() != 1) {
                    JOptionPane.showMessageDialog(null, "Você deve escolher uma esmissora.");
                }
                else if (jtxtNome.getText().trim() == "") {
                    JOptionPane.showMessageDialog(null, "Você deve inserir o nome do departamento.");
                }

            }
        }

    }

}
